package com.aidex.framework.security.filter;

import com.aidex.framework.security.token.MobielCodeAuthenticationToken;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.Optional;

public class MobileCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    protected MobileCodeAuthenticationFilter(String defaultFilterProcessesUrl) {
        super(defaultFilterProcessesUrl);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        if (!Objects.equals(request.getMethod(),"POST")) {
            throw new AuthenticationServiceException("身份验证方法需为:'POST'请求");
        }

        String mobile = Optional.ofNullable(request.getParameter("mobile")).map(String::trim).orElse("");
        String mobileCode = Optional.ofNullable(request.getParameter("mobile")).map(String::trim).orElse("");

        MobielCodeAuthenticationToken authRequest = new MobielCodeAuthenticationToken(mobile, mobileCode);
        authRequest.setDetails(super.authenticationDetailsSource.buildDetails(request));
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
